package com.dianban.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 上传文件
 */
@RestController
@RequestMapping("/file")
public class UploadController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(UploadController.class);

    public static final String ROOT_URL = "/www/wwwroot/";
    public static final String SAVE_DIR = "yun.dianbang-st.com/public/appletUpload/";
    public static final String VISIT_URL = "http://yun.dianbang-st.com/appletUpload/";

    @Autowired
    ResourceLoader loader;

    @ResponseBody
    @RequestMapping(value = "/upload", produces = {"application/json"})
    public ResponseEntity importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        // 控制下不能超过2M，打印下文件大小
        //String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
        String originFileName = file.getOriginalFilename();
        String ext = originFileName.substring(originFileName.lastIndexOf("."), originFileName.length());
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ext;
        String filePath = ROOT_URL + SAVE_DIR + fileName;
        File dir = new File(ROOT_URL + SAVE_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        RandomAccessFile raFile = null;
        BufferedInputStream inputStream = null;
        try {
            //File dirFile = new File(SAVE_DIR, originalFilename);
            File dirFile = new File(filePath);
            raFile = new RandomAccessFile(dirFile, "rw");
            raFile.seek(raFile.length());
            inputStream = new BufferedInputStream(file.getInputStream());
            byte[] buf = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buf)) != -1) {
                raFile.write(buf, 0, length);
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (raFile != null) {
                    raFile.close();
                }
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
        }
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("imgUrl", filePath);
        //resultMap.put("visitImgUrl", VISIT_URL + SAVE_DIR + fileName);
        resultMap.put("visitImgUrl", VISIT_URL + fileName);
        map.put("result", true);
        map.put("data", resultMap);

        // umeditor
        map.put("state", "SUCCESS");
        //map.put("url", filePath);
        map.put("url", "/appletUpload/" + fileName);
        map.put("size", file.getSize());
        map.put("name", fileName);
        map.put("type", file.getContentType());
        map.put("originalName", file.getOriginalFilename());
        logger.info("url:{},size:{},name:{},originalName:{},type:{},", filePath, file.getSize(),
                fileName, file.getOriginalFilename(), file.getContentType());
        return new ResponseEntity(map, HttpStatus.OK);
    }

    @RequestMapping("/show")
    public ResponseEntity showPhotos(String filePath) {
        //HttpHeaders headers=new HttpHeaders();
        //byte[] body = null;
        try {
            // 由于是读取本机的文件，file是一定要加上的， path是在application配置文件中的路径
            return ResponseEntity.ok(loader.getResource("file:" + filePath));
            //body = IOUtils.toByteArray(loader.getResource("file:" + filePath).getInputStream());
            //String fileName = filePath.substring(filePath.lastIndexOf('/')+1, filePath.length());

            //headers.add("Content-Disposition", "attachment;filename="+fileName);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
        //return new ResponseEntity(body, headers, HttpStatus.OK);
    }
}
